<?php

namespace app\index\controller;

use app\common\entity\Config;
use app\common\entity\MywalletLog;
use app\common\entity\OtcMatch;
use app\common\entity\User;
use app\common\service\Market\Auth;
use app\index\model\SendCode;
use think\Request;
use app\common\entity\OtcMarket;
use app\common\entity\Proportion;
use app\common\entity\Image;
use app\common\entity\Mywallet;
use app\common\service\Users\Service;
use think\Db;

class Market extends Base {



    public function index() {
        $proportion = Proportion::where('date', '=', date('Y-m-d', time()))->order('date desc')->field('day_max,day_min,ratio,day_ratio')->find();
        $img = Image::where('types', 2)->order('sort desc,id desc')->select();
        $buy = OtcMarket::alias('m')
            ->join('user u','u.id = m.user_id')
            ->field('u.avatar,m.*')
            ->where('m.trade_type',1)
            ->where('m.status',1)
            ->where('m.num','>',0)
            ->order('m.create_time desc')
            ->select();
        foreach($buy as $k=>$v){
            $buy[$k]['trade'] = OtcMatch::where('market_id',$v['id'])->where('status',3)->sum('total');
        }

        $sell = OtcMarket::alias('m')
            ->join('user u','u.id = m.user_id')
            ->field('u.avatar,m.*')
            ->where('m.trade_type',2)
            ->where('m.status',1)
            ->where('m.num','>',0)
            ->order('m.create_time desc')
            ->select();
        foreach($sell as $k=>$v){
            $sell[$k]['trade'] = OtcMatch::where('market_id',$v['id'])->where('status',3)->sum('total');
        }
        $my_gyg = Mywallet::where('user_id',$this->userId)->value('gyg');
        return json(['code' => 0, 'message' => '获取成功','info'=>['banner' => $img,'proportion' => $proportion,'buy' => $buy,'sell' => $sell,'my_gyg'=>$my_gyg,'can_pay'=>$this->get_pay()]]);

    }

    /**
     * 买入
     */
    public function buy(Request $request) {
        if ($request->isPost()) {
           /* if(!$this->is_pay()){
                return json(['code' => 2, 'message' => '请先绑定收款信息']);
            }*/

            $validate = $this->validate($request->post(), '\app\index\validate\BuyForm');
            if ($validate !== true) {
                return json(['code' => 1, 'message' => $validate]);
            }

            $user = User::where('id', $this->userId)->find();
            if ($user['is_close'] != 1) {
                return json(['code' => 1, 'message' => '您账号禁止购买']);
            }
            if ($user['real_pass'] != 2) {
                return json(['code' => 1, 'message' => '请先实名认证']);
            }




            $config = new Config();

            $sale_min = $config->getValue('sale_min');

            $data = [
                'title'=>$request->post('title'),
                'price'=>$request->post('price'),
                'min'=>$request->post('min'),
                'pay_type'=>$request->post('pay_type'),
                'trade_type'=>1,
                'total'=>$request->post('total'),
                'pay_gyg' => $request->post('total')
            ];

            if ($data['total'] < $sale_min) {
                    return json(['code' => 1, 'message' => '最小交易额 '.$sale_min]);
            }
            //进行购买
            try {
                $model = new OtcMarket();
                $model->addMarketList($this->userId,$data);

                return json(['code' => 0, 'message' => '挂卖成功', 'toUrl' => url('trade/buy')]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'message' => $e->getMessage()]);
            }
        }
    }


    /**
     * 卖出
     */
    public function sale(Request $request)
    {
        if ($request->isPost()) {
            if(!$this->is_pay()){
                return json(['code' => 2, 'message' => '请先绑定收款信息']);
            }
            $user = User::where('id', $this->userId)->find();
            if ($user['is_close'] != 1) {
                return json(['code' => 1, 'message' => '您账号禁止卖出']);
            }
            if ($user['real_pass'] != 2) {
                return json(['code' => 1, 'message' => '请先实名认证']);
            }
            $validate = $this->validate($request->post(), '\app\index\validate\BuyForm');
            if ($validate !== true) {
                return json(['code' => 1, 'message' => $validate]);
            }
            $wallet = Mywallet::where('user_id',$this->userId)->value('gyg');
            $charges = 1+bcmul(Config::getValue('charges'),0.01,4);
            $money = bcmul($request->post('total'),$charges,2);

            if($money > $wallet){
                return json(['code' => 1, 'message' => '余额不足']);
            }
            $data = [
                'title' => $request->post('title'),
                'price' => $request->post('price'),
                'min' => $request->post('min'),
                'pay_type' => $request->post('pay_type'),
                'trade_type' => 2,
                'total' => $request->post('total'),
                'pay_gyg' => $money
            ];

            $config = new Config();
            $sale_min = $config->getValue('sale_min');
            if ($data['total'] < $sale_min) {
                return json(['code' => 1, 'message' => '最小交易额 ' . $sale_min]);
            }

            try {
                $model = new OtcMarket();
                $model->addMarketList($this->userId, $data);
                //扣钱

                MywalletLog::addLog($this->userId,$money,1,'申请挂卖',7,2);
                return json(['code' => 0, 'message' => '挂卖成功', 'toUrl' => url('trade/sale')]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'message' => $e->getMessage()]);
            }
        }
    }


    //求购列表
    public function buyList(Request $request) {
        $limit = $request->get('limit', 20);

        $model = new OtcMarket();
        //$list = $model->where('user_id',$this->userId)->where('trade_type',1)->paginate($limit,false, [
        $list = $model->where('status',1)->where('trade_type',1)->paginate($limit,false, [
            'query' => isset($map) ? $map : []
        ]);

        return json([
            'code' => 0,
            'message' => 'success',
            'data' => $list
        ]);
    }

    //出售列表

    public function saleList(Request $request) {
        $limit = $request->get('limit', 20);

        $model = new OtcMarket();
        //$list = $model->where('user_id',$this->userId)->where('trade_type',2)->paginate($limit,false, [
        $list = $model->where('status',1)->where('trade_type',2)->paginate($limit,false, [
            'query' => isset($map) ? $map : []
        ]);

        return json([
            'code' => 0,
            'message' => 'success',
            'data' => $list
        ]);
    }




    /**
     * 买ta
     */
    public function buyTa(Request $request) {
        if ($request->isPost()) {
           /* if(!$this->is_pay()){
                return json(['code' => 2, 'message' => '请先实名认证']);
            }*/
            $user = User::where('id', $this->userId)->find();
            if ($user['is_close'] != 1) {
                return json(['code' => 1, 'message' => '您账号禁止购买']);
            }
            if ($user['real_pass'] != 2) {
                return json(['code' => 1, 'message' => '请先实名认证']);
            }
            $market_id = intval($request->post('market_id'));
            $num = intval($request->post('num'));
            //密码
            if(!( (new Service())->checkPayPassword($request->post('trad_password'),$user)) ){
                return json(['code'=>1,'message'=>'支付密码错误']);
            }

            try {

                $trade = OtcMatch::buyTa($market_id, $this->userId,$num);
                # 短信提醒卖方
                $matchInfo = OtcMarket::where('id',$market_id)->find();
                $saleUserInfo = User::where('id', $matchInfo['user_id'])->find();
                //$this->sendMsg($saleUserInfo->mobile,'您挂卖的“'.$matchInfo['title'].'”被购买了，请24小时内确认，过期后自动拨币【金运来】');
                $this->sendMsg($saleUserInfo->mobile,'您挂卖的“'.$matchInfo['title'].'”被购买了，请24小时内确认，过期后自动拨币【GYG商城');
                return json(['code' => 0, 'message' => '买入成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'message' => $e->getMessage()]);
            }
        }
    }

    /**
     * 卖ta
     */
    public function saleTa(Request $request) {
        if ($request->isPost()) {
            if(!$this->is_pay()){
                return json(['code' => 2, 'message' => '请先绑定收款信息']);
            }
            $user = User::where('id', $this->userId)->find();
            if ($user['is_close'] != 1) {
                return json(['code' => 1, 'message' => '您账号禁止卖出']);
            }
            if ($user['real_pass'] != 2) {
                return json(['code' => 1, 'message' => '请先实名认证']);
            }

            $market_id = intval($request->post('market_id'));
            $num = intval($request->post('num'));



            //密码
            if(!( (new Service())->checkPayPassword($request->post('trad_password'),$user)) ){
                return json(['code'=>1,'message'=>'支付密码错误']);
            }

            $money = bcadd(bcmul($num,bcmul(Config::getValue('charges'),0.01,4),4),$num);

            $gyg = Mywallet::where('user_id',$this->userId)->value('gyg');
            if($money > $gyg){
                return json(['code'=>1,'message'=>'余额不足']);
            }

            try {
                $trade = OtcMatch::saleTa($market_id, $this->userId,$num,$money);
                MywalletLog::addLog($this->userId, $money, 1, 'OTC交易卖出', 7, 2);
                # 短信
                $matchInfo = OtcMarket::where('id',$market_id)->find();
                $byUserInfo = User::where('id', $matchInfo['user_id'])->find();
                //$send = $this->sendMsg($byUserInfo->mobile,'您挂买的“'.$matchInfo['title'].'”有出售，请24小时内确认，过期后订单失效【金运来】');
                $send = $this->sendMsg($byUserInfo->mobile,'您挂买的“'.$matchInfo['title'].'”有出售，请24小时内确认，过期后订单失效【GYG商城】');
                return json(['code' => 0, 'message' => '卖出成功','send'=>$send]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'message' => $e->getMessage()]);
            }
        }
    }



    //求购列表
    public function myBuyList(Request $request) {
        $limit = $request->get('limit', 20);

        $model = new OtcMarket();
        $list = $model->where('user_id',$this->userId)->where('trade_type',1)->paginate($limit,false, [
            'query' => isset($map) ? $map : []
        ]);

        return json([
            'code' => 0,
            'message' => 'success',
            'data' => $list
        ]);
    }

    //出售列表

    public function mySaleList(Request $request) {
        $limit = $request->get('limit', 20);

        $model = new OtcMarket();
        $list = $model->where('user_id',$this->userId)->where('trade_type',2)->paginate($limit,false, [
            'query' => isset($map) ? $map : []
        ]);

        return json([
            'code' => 0,
            'message' => 'success',
            'data' => $list
        ]);
    }




//短信通知
    private function sendMsg($mobile,$msg){

        $model = new SendCode($mobile, 'market');

        if ($model->sendInfo($msg)) {
            return ['code' => 0, 'message' => '你的验证码发送成功'];
        }

        return ['code' => 1, 'message' => '验证码发送失败'];
    }


                                                          #我的#
    //-------------------------------------------------邪恶的分割线-------------------------------------------------------//

    #我的
    public function my(){
        $user =  User::where('id',$this->userId)->field('avatar,mobile,nick_name')->find();
        return json(['code' => 0, 'info' =>$user]);
    }

    public function myMatch(Request $request){
        $status = $request->post('status',1);
        if($status == 3){
            $status = '3,4,5,6';
        }
        $list = OtcMatch::where('uid|from_id',$this->userId)->where('status','in',$status)->order('create_time desc')->paginate(15,false, [
            'query' => isset($map) ? $map : []
        ]);
        foreach($list as $k=>$match){
            if($match['uid'] == $this->userId){
                $list[$k]['is_sale'] = true;
            }else{
                $list[$k]['is_sale'] = false;
            }
        }
        return json(['code' => 0,'message'=>'获取成功','info' =>$list]);
    }
    #订单详情
    public function matchDetail(Request $request){
        $id = $request->post('id');
        $match = OtcMatch::where('id',$id)->find();
        if($match['uid'] == $this->userId){
            $is_sale = true;
        }else{
            $is_sale = false;
        }

        $byInfo = User::where('id',$match['from_id'])->field('mobile,zfb,wx,card_number')->find();
        $saleInfo = User::where('id',$match['uid'])->field('mobile,wx,wx_name,wx_image_url,zfb,zfb_name,zfb_image_url,card_open,card_branch,card_number,card_name')->find();

        if(strstr($match['pay_type'], '1') == false){
            $saleInfo['wx'] = null;
            $saleInfo['wx_name'] = null;
            $saleInfo['wx_image_url'] = null;
        }
        if(strstr($match['pay_type'], '2') == false){
            $saleInfo['zfb'] = null;
            $saleInfo['zfb_name'] = null;
            $saleInfo['zfb_image_url'] = null;
        }
        if(strstr($match['pay_type'], '3') == false){
            $saleInfo['card_open'] = null;
            $saleInfo['card_branch'] = null;
            $saleInfo['card_number'] = null;
            $saleInfo['card_name'] = null;
        }
        $time = Config::getValue('time_end')*3600;
        $end_time = $time+strtotime($match['create_time']) - time();
        return json(['code' => 0,'message'=>'获取成功','info' =>['match'=>$match,'byInfo'=>$byInfo,'saleInfo'=>$saleInfo,'is_sale'=>$is_sale,'time'=>$end_time]]);
    }
    #支付凭证
    public function pay_img(Request $request){
        $id = $request->post('id');
        $pay_img = $request->post('pay_img');
        $match = OtcMatch::where('id',$id)->find();
        if($match['status'] != 1){
            return json(['code' => 0,'message'=>'订单状态错误']);
        }
        $update = OtcMatch::where('id',$id)->update(['pay_img'=>$pay_img,'pay_time'=>time(),'status'=>2]);
        if ($update) {
            return json(['code' => 0, 'message' => '操作成功']);
        }
        return json(['code' => 1, 'message' => '操作失败']);
    }
    #确认收款
    public function complete(Request $request){
        //密码
        $user = User::where('id',$this->userId)->find();
        if(!( (new Service())->checkPayPassword($request->post('trad_password'),$user)) ){
            return json(['code'=>1,'message'=>'支付密码错误']);
        }
        $id = $request->post('id');
        $match = OtcMatch::where('id',$id)->find();
        if($match['status'] !=2){
            return json(['code' => 0,'message'=>'订单状态错误']);
        }
        if(OtcMatch::complete($id)){
            return json(['code' => 0, 'message' => '操作成功']);
        }
        return json(['code' => 1, 'message' => '操作失败']);
    }
    public function cancel(Request $request){
        $id = $request->post('id');
        $market = OtcMarket::where('id',$id)->where('user_id',$this->userId)->find();
        if($market['status'] !=1){
            return json(['code' => 0,'message'=>'订单状态错误']);
        }
        if($market['trade_type'] == 2){
            $status2 = OtcMatch::where('market_id',$id)->where('status',2)->count();
            if($status2 > 0){
                return json(['code' => 1, 'message' => '还有'.$status2.'个待确定订单，请先处理']);
            }
            $status6 = OtcMatch::where('market_id',$id)->where('status',6)->count();
            if($status6 > 0){
                return json(['code' => 1, 'message' => '还有'.$status6.'个申诉中订单，请先处理']);
            }
        }
        $update = OtcMarket::where('id',$id)->update(['update_time'=>time(),'status'=>3]);
        if ($update) {
            if($market['trade_type'] == 2){
                MywalletLog::addLog($this->userId, $market['pay_gyg'], 1, 'OTC取消卖出', 7, 1);
                OtcMatch::where('market_id',$id)->where('status',1)->update(['status'=>4,'end_time'=>time()]);

            }
            return json(['code' => 0, 'message' => '取消成功']);
        }
        return json(['code' => 1, 'message' => '取消失败']);
    }
    #申诉
    public function appeal(Request $request){
        $date = [
            'match_id'=>$request->post('id'),
            'content'=>$request->post('content'),
            'img'=>$request->post('img'),
            'create_time'=>time(),
            'user_id'=>$this->userId,
        ];
        $insert = Db::name('otc_appeal')->insert($date);
        if ($insert) {
            $match = OtcMatch::where('id',$request->post('id'))->update(['status'=>6]);
            return json(['code' => 0, 'message' => '申诉成功，请耐心等待后台审核']);
        }
        return json(['code' => 1, 'message' => '申诉失败']);
    }
    #申诉列表
    public function appeal_list(Request $request){
        $list = Db::name('otc_appeal')->where('user_id',$this->userId)->order('create_time desc')->paginate(15,false, [
            'query' => isset($map) ? $map : []
        ])->each(function($item){
            $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
            return $item;
        });
        return json(['code' => 0,'message'=>'获取成功','info' =>$list]);
    }

    #是否绑定支付方式
    private function is_pay(){
        $user = User::where('id',$this->userId)->find();
        if(!$user['wx_name'] && !$user['zfb_name'] && !$user['card_name']){
            return false;
        }
        return true;
    }
    #获取支付方式
    private function get_pay(){
        $user = User::where('id',$this->userId)->find();
        $can = [];
        if($user['wx_name']) $can[] = 'wx';
        if($user['zfb_name']) $can[] = 'zfb';
        if($user['card_name']) $can[] = 'card';
        return $can;
    }

    #判断是否可以购买
    public function can_trade(Request $request){

        if($this->is_pay() == false){
            return json(['code' => 1,'message'=>'请先绑定支付方式']);
        }
        $get_pay = $this->get_pay();
        $market = OtcMarket::where('id',$request->post('id'))->find();
        $trade = false;
        $pay_type = [];
        if(strstr($market['pay_type'], '1')){
            if(!in_array('wx',$get_pay)){
                $pay_type[] = '微信';
            }else{
                $trade = true;
            }
        }
        if(strstr($market['pay_type'], '2')){
            if(!in_array('zfb',$get_pay)){
                $pay_type[] = '支付宝';
            }else{
                $trade = true;
            }
        }
        if(strstr($market['pay_type'], '3')){
            if(!in_array('card',$get_pay)){
                $pay_type[] = '银行卡';
            }else{
                $trade = true;
            }
        }
        if($trade){
            return json(['code' => 0,'message'=>'可以购买']);
        }else{
            return json(['code' => 1,'message'=>'请先绑定'.implode(',',$pay_type).'支付方式']);
        }
    }
}
